//index.js
//获取应用实例
const app = getApp()
const commonFunction = require("../../common/common.js")
const QQMapWX = require("../../qqmap-wx-jssdk.js")
const api = require("../../config/api.js")

Page({
  data: {
    signIn: {
      time: '',
      //true上班状态,false下班状态
      state: false,
      address: "",
      userId: "",
    },
    daka: "",
    longitude: "",
    latitude: "",
    signInList: [],
    nowTime: ""
  },
  onShow: function () {
    console.log(app.globalData.userId)
    this.setData({
      // state: this.data.signIn.state ? false : true,
      daka: !this.data.signIn.state ? "上班打卡" : "下班打卡",
      signIn: {

        userId: app.globalData.userId
      },
      nowTime: commonFunction.formatTime(new Date())
    })

    if (app.globalData.userId > 0) {
      this.findSignInList()
    }


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.stopPullDownRefresh()

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad()
  },
  //打卡时间显示
  onLoad: function () {
    var that = this;
    var interval = setInterval(function () {
      that.setData({
        nowTime: commonFunction.formatTime(new Date())
      })
    }, 1000);
  },
  onReady: function () {

  },
  //打卡
  sign_In: function () {
    var that = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting["scope.userLocation"]) {
          wx.showToast({
            title: '请在设置打开获取位置权限',
            icon:"none"
          })
          console.log(res)
          wx.authorize({
            scope: 'scope.userLocation',
            success () {
            }
          })
        }
      }
    })
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res)
        // 2.2 获取用户位置成功后，将会返回 latitude, longitude 两个字段，代表用户的经纬度位置
        var lat1 = res.latitude
        var lng1 = res.longitude
        //  将获取到的 经纬度传值给 getAddress 解析出 具体的地址
        // that.getAddress(res.latitude, res.longitude)
        that.getAddress(lat1, lng1)
      },
    })
  },
  getAddress(latitude, longitude) {
    var that = this
    // 生成 QQMapWX 实例
    let qqmapsdk = new QQMapWX({
      key: 'VIIBZ-2SIE2-AU2UT-CZO7C-JTKCV-QQBAQ'
    })

    // reverseGeocoder 为 QQMapWX 解析 经纬度的方法
    qqmapsdk.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      success(res1) {
        console.log(res1)
        //保存打卡信息
        that.saveDaKa(res1)
      }
    })
  },

  //保存打卡信息
  saveDaKa: function (res1) {
    console.log(this.data.signIn)
    var that = this
    if (app.globalData.userId == null) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return;
    }
    //存入本页
    that.setData({
      signIn: {
        userId: app.globalData.userId,
        state: that.data.signIn.state,
        time: commonFunction.formatTime(new Date()),
        address: res1.result.formatted_addresses.recommend
      }
    })
    wx.request({
      url: api.saveDaKa,
      data: JSON.stringify(that.data.signIn),
      method: "POST",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        wx.showToast({
          title: '打卡成功',
        })
        that.setData({
          signIn: {
            state: !res.data[res.data.length - 1].state,
          },
          signInList: res.data,
          daka: !res.data[res.data.length - 1].state ? "上班打卡" : "下班打卡"
        })
      }
    })

  },
  //查询打卡信息
  findSignInList: function () {

    var that = this
    wx.request({
      url: api.getDaKa + "?userId=" + this.data.signIn.userId,
      method: "GET",
      data: this.data.signIn.userId,
      success: function (res) {
        that.setData({
          signIn: {
            state: true
          }
        })
        if (res.data.length != 0) {
          that.setData({
            signIn: {
              state: !res.data[res.data.length - 1].state,
            },
            signInList: res.data,
            daka: !res.data[res.data.length - 1].state ? "上班打卡" : "下班打卡"
          })

          if (res.data[res.data.length - 1].state) {
            that.setData({
              signIn: {
                state: false
              }
            })
          }
        }

      }
    })
  }

})





// 计算两地之间的距离
function juli(lat1, lng1, lat2, lng2) {
  console.log(lat1, lng1, lat2, lng2)
  var radLat1 = lat1 * Math.PI / 180.0;
  var radLat2 = lat2 * Math.PI / 180.0;
  var a = radLat1 - radLat2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;
  s = Math.round(s * 10000) / 10000;
  return s
}